#include"InetAddress.h"
#include<strings.h>
#include<string.h>

InetAddress::InetAddress(uint16_t port,std::string ip)
{
    bzero(&addr_,sizeof addr_);
    addr_.sin_family=AF_INET;
    addr_.sin_port=htons(port);
    addr_.sin_addr.s_addr=inet_addr(ip.c_str());
}
std::string InetAddress::toIP() const
{
    char buf[64]={0};
    //inet_ntop()将一个二进制的ip地址转换成点分十进制的字符串形式并存储到特定的缓冲区中
    ::inet_ntop(AF_INET,&addr_.sin_addr,buf,sizeof(buf));
    return buf;
}
uint16_t InetAddress::toPort()const
{
    uint16_t port=ntohs(addr_.sin_port);
    return port;
}
std::string InetAddress::toIpPort() const
{
    char buf[64]={0};
    //inet_ntop()将一个二进制的ip地址转换成点分十进制的字符串形式并存储到特定的缓冲区中
    ::inet_ntop(AF_INET,&addr_.sin_addr,buf,sizeof(buf));
    size_t len=strlen(buf);
    uint16_t port=ntohs(addr_.sin_port);
    sprintf(buf+len,":%u",port);
    return buf;
}

/* #include<iostream>
int main()
{
    InetAddress cli(8080);
    std::cout<<cli.toIP()<<":"<<cli.toPort()<<std::endl;
    std::cout<<cli.toIpPort()<<std::endl;
    return 0;
} */